package com.jd.fruit.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Record;

/**
 * 引用插件处理工具
 * 
 * @author lishunfeng
 * 
 */
public class WebLinkUtil {
	protected static Prop prop = null;

	/**
	 * 查询百度地图定位
	 * 
	 * @param addr
	 * @return
	 * @throws IOException
	 */
	public static Object[] getCoordinate(String addr) throws IOException {
		String lng = null;// 经度
		String lat = null;// 纬度
		String address = null;
		try {
			address = java.net.URLEncoder.encode(addr, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String key = "795fc5cc3d88dae90111607912018cfc";
		String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s",address, key);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		InputStreamReader insr = null;
		BufferedReader br = null;
		try {
			httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
			if (httpsConn != null) {
				insr = new InputStreamReader(httpsConn.getInputStream(),
						"UTF-8");
				br = new BufferedReader(insr);
				String data = null;
				int count = 1;
				while ((data = br.readLine()) != null) {
					if (count == 5) {
						lng = (String) data.subSequence(data.indexOf(":") + 1,
								data.indexOf(","));// 经度
						count++;
					} else if (count == 6) {
						lat = data.substring(data.indexOf(":") + 1);// 纬度
						count++;
					} else {
						count++;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (insr != null) {
				insr.close();
			}
			if (br != null) {
				br.close();
			}
		}
		return new Object[] { lng, lat };
	}
	/**
	 * 获取IP归属地
	 * @param request
	 * @return
	 */
	public static String iPSearch(HttpServletRequest request) {
		String addrStr = ipSearchOpr(request);
		String provinceName="";
		if(addrStr.indexOf("{")!=-1){
		addrStr=addrStr.substring(addrStr.indexOf("{"), addrStr.lastIndexOf("}")+1);
	    JSONObject jsonStr=JSONObject.parseObject(addrStr);
		    if(jsonStr.containsKey("province")){
		    	provinceName=jsonStr.getString("province");
		    }else{
		    	provinceName="无法识别";
		    }
	    }else{
	    	provinceName="无法识别";
	    }
		return provinceName;
	}
	private static String ipSearchOpr(HttpServletRequest request) {
		String ip = WebContextUtil.getClientIpAddr(request);
		HttpURLConnection urlConection = null;
		prop = PropKit.use("webservice.properties", DictUtil.encoding);
		String webserviceUrl = prop.get("ipAddressUrl");

		URL url = null;
		try {
			url = new URL(webserviceUrl);
			urlConection = (HttpURLConnection) url.openConnection();
			urlConection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
			urlConection.setReadTimeout(2000);// 设置读取数据超时时间，单位毫秒
			urlConection.setDoOutput(true);// 是否打开输出流 true|false
			urlConection.setDoInput(true);// 是否打开输入流true|false
			urlConection.setRequestMethod("POST");// 提交方法POST|GET
			urlConection.setUseCaches(false);// 是否缓存true|false
			urlConection.connect();// 打开连接端口
			DataOutputStream out = new DataOutputStream(urlConection
					.getOutputStream());
			out.writeBytes("format=js&ip=" + ip);// 写数据,也就是提交你的表单
													// name=xxx&pwd=xxx
			out.flush();// 刷新
			out.close();// 关闭输出流
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					urlConection.getInputStream(), DictUtil.encoding));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			urlConection.disconnect();
			return buffer.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
